<template>
  <div class="mod-config" style="margin-top: 30px">
    <div>
      <el-button
        type="primary"
        @click="checkPerson('sjkh')"
        :disabled="isImport"
      >新增人员</el-button> <!--如果是由w维导入的数据，不可以追加数据-->

      <el-button
        v-if="permissions.rckhsjkhdx_del"
        type="primary"
        @click="deleteBatch"
      >删除</el-button>

      <el-button type="primary" @click="openImport('allColumn')" style="float:right;" v-if="!editShow">导入</el-button><!--只有在列表新增的时候显示-->
      <el-button type="primary" @click="download" style="float:right;" v-if="!editShow">导出模板</el-button>

      <!--<el-button type="primary" @click="openImport" style="float:right;">导入加扣分值</el-button>
      <el-button type="primary" @click="exportXlsx" style="float:right;">导出加扣模板</el-button>-->

    </div>


    <div v-if="showBlock">
      <!--提示导入错误信息-->
      <el-alert
        style="margin-top: 10px"
        title="错误提示"
        type="error"
        v-if="tipsShow"
        @close="true"
        show-icon>
        <template ><!-- :description="errorContent"-->
            <div v-for="item in errorContent">{{item}}</div>
         </template>
      </el-alert>

      </el-alert>
      <el-table
        style="width: 100%; margin-top: 15px"
        :data="dataList"
        border
        v-show="tabType == 1"
        v-loading="dataListLoading"
        @selection-change="handleSelectionChange"
        ref="table2"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column
          type="index"
          width="80"
          header-align="center"
          align="center"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="username"
          header-align="center"
          align="center"
          width="90"
          label="员工编号"
          show-overflow-tooltip
        >
         <!-- <template slot-scope="scope">
            <el-input v-model="scope.row.ygbh" placeholder="员工编号" />
          </template>-->
        </el-table-column>

        <el-table-column
          prop="realname"
          header-align="center"
          align="center"
          width="120"
          label="姓名"
          show-overflow-tooltip
        >
        <!--  <template slot-scope="scope">
            <el-input
              v-model="scope.row.name"
              placeholder="姓名"
            />
          </template>-->
        </el-table-column>
        <el-table-column
          prop="deptName"
          header-align="center"
          align="center"
          width="120"
          label="部门"
          show-overflow-tooltip
        >
         <!-- <template slot-scope="scope">
            <el-input
              v-model="scope.row.bm"
              placeholder="部门"
            />
          </template>-->
        </el-table-column>
        <el-table-column
          v-if="show"
          prop="deptid"
          header-align="center"
          align="center"
          label="部门id"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="lb"
          width="140"
          header-align="center"
          align="center"
          label="类别"
        >
          <template slot-scope="scope">
          <!--  <div v-if="editFlag == 0">
                  <span v-for="item in lbsList">
                    <span v-if="item.value == scope.row.lb">
                      {{ item.name }}
                    </span>
                  </span>
            </div>-->
            <!--导入 importFlag 1导入 -by w维-->
            <el-input v-if="scope.row.importFlag == '1' " v-model="scope.row.lbms"></el-input>

            <!--修改界面 并且是导入的数据,不可修改-->
            <span v-if="editFlag == 1 && scope.row.lb==null ">{{scope.row.lbms}}</span>

            <!--新增-->
            <el-select
              v-model="scope.row.lb"
              v-if="editFlag == 0 && scope.row.importFlag != '1' "
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              fatherLb(val,scope.row, scope.$index)
                  })"
            >
              <el-option
                v-for="(item, index) in lbsList"
                :key="index"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
            <!--修改-->
            <el-select
              v-model="scope.row.lb"
              v-if="editFlag == 1 && scope.row.importFlag != '1' && scope.row.lb!=null "
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              savePropertyLb(val,scope.row, scope.$index)
                  })"


            >
              <el-option
                v-for="(item, index) in lbsList"
                :key="index"
                :label="item.name"
                :value="String(item.value)"
              ></el-option>
            </el-select>

          </template>
        </el-table-column>
        <el-table-column
          prop="yj"
          width="140"
          header-align="center"
          align="center"
          label="依据"
        >
          <template slot-scope="scope">
            <!--导入 importFlag 1导入 -by w维-->
            <el-input v-if="scope.row.importFlag == '1' " v-model="scope.row.yjms"></el-input>
            <!--修改界面 并且是导入的数据,不可修改-->
            <span v-if="editFlag == 1 && scope.row.lb==null ">{{scope.row.yjms}}</span>
            <!--新增-->
            <el-select
              v-model="scope.row.yj"
              v-if="editFlag == 0 && scope.row.importFlag != '1'"
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              fatherYj(val,scope.row, scope.$index)
                  })"
            >
              <el-option
                v-for="(item, index) in scope.row.yjsList"
                :key="index"
                :label="item.name"
                :value="String(item.value)"
              ></el-option>
            </el-select>
            <!--修改-->
            <el-select
              v-model="scope.row.yj"
              v-if="editFlag == 1 && scope.row.importFlag != '1' && scope.row.lb!=null"
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              savePropertyYj(val,scope.row, scope.$index)
                  })"
            >
              <el-option
                v-for="(item, index) in scope.row.yjsList"
                :key="index"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="bz"
          header-align="center"
          align="center"
          width="120"
          label="标准"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
             <el-input v-if="scope.row.importFlag == '1'" v-model="scope.row.bz"></el-input>
             <span v-else>{{scope.row.bz}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="zbgz"
          header-align="center"
          align="center"
          width="100"
          label="指标规则"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input v-if="scope.row.importFlag == '1'" v-model="scope.row.zbgz"></el-input>
            <span v-else>{{scope.row.zbgz}}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="jjxId"
          header-align="center"
          align="center"
          min-width="140"

          label="奖金项"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!--导入 importFlag 1导入 -by w维-->
            <el-input v-if="scope.row.importFlag == '1' " v-model="scope.row.jjx"></el-input>
            <!--修改界面 并且是导入的数据,不可修改-->
            <span v-if="editFlag == 1 && scope.row.lb==null ">{{scope.row.jjx}}</span>
            <!--新增-->
            <el-select
              v-model="scope.row.jjxId"
              v-if="editFlag == 0 && scope.row.importFlag != '1'"
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              fatherJjx(val,scope.row, scope.$index)
                  })"
            >
              <el-option
                v-for="(item, index) in jjxsList"
                :key="index"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
            <!--修改-->
            <el-select
              v-model="scope.row.jjxId"
              v-if="editFlag == 1 && scope.row.importFlag != '1' && scope.row.lb!=null"
              placeholder="请选择"
              class="xiaLa"
              style="width: 100%"
              :clearable="true"
              @change="((val)=>{
              savePropertyJjx(val,scope.row, scope.$index)
                  })"
            >
              <el-option
                v-for="(item, index) in jjxsList"
                :key="index"
                :label="item.name"
                :value="Number(item.value)"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="jkjj"
          header-align="center"
          align="center"
          min-width="120"
          fixed="right"
          label="加扣奖金"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input
              v-if="editFlag == 0"
              @input="fatherJkjj(scope.row, scope.$index)"
              v-model="scope.row.jkjj"
              placeholder="加扣奖金"
            />

            <el-input
              v-if="editFlag == 1  && scope.row.lb!=null"
              v-model="scope.row.jkjj"

              placeholder="加扣奖金"
              @input="savePropertyJkjj(scope.row, scope.$index)"
            />
            <!--导入的数据不可修改-->
            <span v-if="editFlag == 1 && scope.row.lb==null">{{scope.row.jkjj}}</span>


          </template>
        </el-table-column>
        <el-table-column
          prop="jkfz"
          min-width="120"
          header-align="center"
          align="center"
          fixed="right"
          label="加扣分值"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input
              v-if="editFlag == 0"
              v-model="scope.row.jkfz"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
              @blur="fatherJkfz(scope.row, scope.$index)"
              placeholder="加扣分值"
            />
            <el-input
              v-if="editFlag == 1 && scope.row.lb!=null"
              v-model="scope.row.jkfz"
              placeholder="加扣分值"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
              @blur="savePropertyJkfz(scope.row, scope.$index)"
            />
            <!--导入的数据不可修改-->
            <span v-if="editFlag == 1 && scope.row.lb==null">{{scope.row.jkjj}}</span>
          </template>
        </el-table-column>
          <el-table-column
            prop="yjkId"
            v-if="show"
            header-align="center"
            align="center"
            width="100"
            label="依据库id"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
          prop="lbms"
          v-if="show"
          header-align="center"
          align="center"
          width="100"
          label="类别描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="yjms"
          v-if="show"
          header-align="center"
          align="center"
          width="100"
          label="依据描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="ygid"
          v-if="show"
          header-align="center"
          align="center"
          width="100"
          label="员工编号"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="jjx"
          v-if="show"
          header-align="center"
          align="center"
          width="100"
          label="奖金项名称"
          show-overflow-tooltip
        >
        </el-table-column>
      </el-table>
    </div>
    <UserCommonSelect v-if="usercomment" ref="usercomment" @submitfy="submitfy"></UserCommonSelect>
    <el-dialog width="40%" title="导入" :visible.sync="innerVisible" append-to-body>
      <el-row class="mb10" style="height: 10vh;" :gutter="10">
        <el-col :span="4">
          <el-upload
            style="margin-left: 8px;"
            class="upload-demo"
            action
            :on-change="handleChange"
            :show-file-list="false"
            :on-remove="handleRemove"
            :file-list="fileListUpload"
            :limit="limitUpload"
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :auto-upload="false"
            ref="uploadversion"
          >
            <el-button type="primary" plain class="fr">导入</el-button>
          </el-upload>
        </el-col>
        <el-col  :span="12" v-if="!allColumn">
            <span style="color:red;">加扣奖金:为正整数 例:8</span>
        </el-col>
        <el-col  :span="12"  v-if="!allColumn">
          <span style="color:red;">加扣分值:为2位小数正数 例:0.26</span>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>

import UserCommonSelect from "@/views/dailyExamine/components/usercomment-selectCopy-cjsjkh";//人员选择的组件
import {
    getLbSelect,
    getById,
    getKhdxList,
    putObj,
    deleteChildEvent,
    getJjxSelect,
    exportExcel,
    importExcel
} from "@/api/dailyExamine/eventExamine/event.js";
import { mapGetters, mapState } from "vuex";
import store from "@/store";
import XLSX from "xlsx";
export default {
  name: "zbcj-form",
  components: {
      UserCommonSelect
  },
  props: {
     editShow: {
       type: Number,
       default: 0
     }
  },
  /*props: {
      getZbgz: String,
      getJkfbz:String
  },*/
  data() {
    return {
      headers: {
          Authorization: "Bearer " + store.getters.access_token
      },
      editFlag: 0,
      show:false,
      showBlock: true,
      dataForm: {},
      tabType: "1",
      radio: "1",
      dataList: [],
      dataListLoading: false,
      dialogVisible: false,
      form: {},
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      mbId: "",
      mbName: "",
      sjkhId:"",
      type: 0,
      index: 1,
      otherJkfz:'',
      usercomment: false, //人员选择显隐
      lbsList: [],
      //yjsList: [],
      jjxsList:[],
     /* jjxsList: [
          { name: "奖金项1", value: "0" },
          { name: "奖金项2", value: "1" },
          { name: "奖金项3", value: "2" },
      ],*/
      isChangeType:"",
      innerVisible: false,
      fileListUpload: [],
      limitUpload: 3,
      accountList: [],
      allColumn:false,//导入全部列
      isImport:false ,//如果是王维写的接口导入的数据（全部列导入），则控制[新增人员]按钮失效，不可追加数据
      errorContent:'',//导入数据错误信息提示
      tipsShow:false
    };
  },
  computed: {
      ...mapGetters(["permissions"])

  },
  watch: {
      eventzxForm: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.showBlock = false;
          this.$nextTick(res=>{
            this.showBlock = true;
          })
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
      this.getLb();//类别
      this.getjjx();
  },
  methods: {
    init(row, type) {
      this.getDataList();
    },
    // 勾选数据
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },
    exportXlsx() {
      this.$message.closeAll();
      this.$message.success("下载成功!");
      window.location.href = "../../static/jkfzmb.xls";
    },
    openImport(type) {
        if (type=='allColumn'){
            this.allColumn = true ;
        }else{
            this.allColumn = false ;
        }

      this.innerVisible = true;
    },
    // excel表上传
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      let fileName = file.raw.name;
      let fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
      // 判断上传文件格式
      if (this.fileTemp) {
        if (fileType == "xlsx" || fileType == "xls") {
         if (this.allColumn){ //走导入全部列的接口 by  my
            this.importAllColumn(this.fileTemp);
         }else{//走导入分数列的接口 by hy
             this.importf(this.fileTemp);
             this.$message.success("导入成功");
         }
          this.innerVisible = false;
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！"
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！"
        });
      }
    },
    //导入的方法
    importf(obj) {
      this.dialogVisible = true;
      let _this = this;
      let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          // outdata就是你想要的东西 excel导入的数据
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          // excel 数据再处理
          let arr = [];
          outdata.map(v => {
            // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
            let jsonString = JSON.stringify(v)
              .replace(/\//g, "")
              .replace(/\s/gi, "");
            //debugger;
            v = JSON.parse(jsonString);
            let obj = {};
            obj.cyrUserId = v.员工编号;
            obj.jkjj = v.加扣奖金;
            obj.jkfz = v.加扣分值;
            arr.push(obj);
          });
          _this.accountList = [...arr];

          let temp1 = [];
          _this.accountList.map(it => {
            temp1.push({
              cyrUserId: it.cyrUserId,
              jkjj: it.jkjj,
              jkfz: it.jkfz,
            });
          });
          //console.log(temp1)
          let a = [];
          _this.dataList.map((it,index) => {
            temp1.map((itt,indexs) => {
              if (indexs == index) {

                _this.$set(it, "jkjj", itt.jkjj);
                _this.$set(it, "jkfz", itt.jkfz);

              }
            })


          });

        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }

      let uploadFilesArr = this.$refs.uploadversion.uploadFiles; //上传文件列表
      if(uploadFilesArr.length ==0){
      }else{
        this.$refs.uploadversion.uploadFiles =[]

      }

    },
    //导入的方法(全部列)
    importAllColumn(obj) {
      this.dialogVisible = true;
      let _this = this;
      let inputDOM = this.$refs.inputer; // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          // outdata就是你想要的东西 excel导入的数据
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

          console.log("outdata",outdata)

          // excel 数据再处理
          let arr = [];
          outdata.map(v => {
            // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
            let jsonString = JSON.stringify(v).replace(/\//g, "").replace(/\s/gi, "");
            v = JSON.parse(jsonString);
            let obj = {};
            obj.username = v["*员工编号"];
            obj.realname = v["*姓名"];
            obj.lbms = v["类别"];
            obj.yjms = v["依据"];
            obj.bz = v["标准"]; //可以为空
            obj.zbgz = v["*指标规则"];//必须为 正指标 负指标
            obj.jjxId = v["*奖金项id"];
            obj.jjx = v["*奖金项"];
            obj.jkfz = v["加扣分值"];//只能是正数
            obj.jkjj = v["加扣奖金"];//只能是正数
            arr.push(obj);
          });

          console.log( "_this.dataList",_this.dataList)
            _this.dataListLoading = true ;
            importExcel(arr).then(r => {

                if (r.data.msg == "failed"){
                    _this.tipsShow =  true ;
                    _this.errorContent = r.data.data ;
                }else{
                    _this.dataList = r.data.data;
                    _this.isImport = true ;
                    _this.tipsShow = false ;
                }
                _this.dataListLoading = false;
            })
            .catch(() => {
                _this.dataListLoading = false;
            })

          // this.$message.success("导入成功");

          // let temp1 = [];
          // _this.accountList.map(it => {
          //   temp1.push({
          //     cyrUserId: it.cyrUserId,
          //     jkjj: it.jkjj,
          //     jkfz: it.jkfz,
          //   });
          // });
          // //console.log(temp1)
          // let a = [];
          // _this.dataList.map((it,index) => {
          //   temp1.map((itt,indexs) => {
          //     if (indexs == index) {
          //       _this.$set(it, "jkjj", itt.jkjj);
          //       _this.$set(it, "jkfz", itt.jkfz);
          //     }
          //   })
          // });

        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }

      let uploadFilesArr = this.$refs.uploadversion.uploadFiles; //上传文件列表
      if(uploadFilesArr.length ==0){
      }else{
        this.$refs.uploadversion.uploadFiles =[]

      }

    },
    // 移除excel表
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
      //获取类别下拉选项
    getLb(){
        getLbSelect(Object.assign({
            yjkfl: 'ry'
        })).then(r => {
            let list=[];
            r.data.data.forEach((ele) => {
                let item = {
                    name:ele.fl,
                    value:ele.id
                }
                this.lbsList.push(item);

            });
            //this.lbsList = list;
        });
    },
      getjjx(){
          getJjxSelect().then(r => {
              let list=[];
              r.data.data.forEach((ele) => {
                  let item = {
                      name:ele.jjxMc,
                      value:ele.id
                  }
                  this.jjxsList.push(item);

              });
              //this.lbsList = list;
          });
      },
    selectSecondSelect(){
        //选择的时候强制刷新
        this.$forceUpdate()
    },
    //修改列表展示
    getList(data){
        this.editLock();
         data.map(it =>{
            if(it.yj != null && it.yj != ""){
                let item = {
                    name:it.yjms,
                    value:it.yj
                };
                it.yjsList = [];
                it.yjsList.push(item);
            }
        })
        this.dataList = data.slice(0,data.length);
        this.isImport = (this.dataList.length>0 && this.dataList[0].lb == null) ? true : false ; //编辑界面，如果是导入进来的数据，lb字段是null,此时的数据不可追加新数据，【新增人员】按钮失效
    },
    //修改状态
    editLock() {
        this.editFlag = 1;
    },
    savePropertyLb(val,row, index) {

            let data = [];
            data = this.$refs.table2.selection;
            if(data.length != 0){
                let  checked = [];
                let  inputId = row.id;
                data.forEach((ele) => {
                    checked.push(ele.id);
                });
            if(val != "" && val != null && val != undefined){
                data.map(it => {

                    if(checked.includes(inputId)){

                        it.lb=row.lb;

                        //改
                        it.zbgz =''
                        it.bz =''
                        it.yjkId =''
                        it.yj =''
                        it.yjsList = []

                        getById(row.lb).then(r => {
                            getLbSelect(Object.assign({
                                yjkfl: 'ry',
                                fl: r.data.data.fl
                            })).then(rr => {
                                it.yjsList = [];
                                rr.data.data.map(itt => {
                                    let item = {
                                        name:itt.yj,
                                        value:itt.id
                                    }

                                    it.yjsList.push(item);
                                });

                            });
                        });
                    }

                });
            }else{
                data.map(it => {

                    if(checked.indexOf(inputId) != -1){

                        it.lb = '';
                        //改
                        it.zbgz =''
                        it.bz =''
                        it.yjkId =''
                        it.yj =''
                        it.yjsList = []

                    }

                });
            }
        }
        //未选中的
        if(val != "" && val != null && val != undefined){
            /*
            //两数组对象，去重复，留下一个数组对象
            const arrayObject = this.$refs.table2.selection.concat(this.dataList)
                      let arrys= this.unique(arrayObject);
                      console.log(arrys)*/
            /*
              //两数组对象，获取相同的数组对象
              let a = [];

              for (let i = 0, length = this.dataList.length; i < length; i++) {
                  for (let j = 0, l = this.$refs.table2.selection.length; j < l; j++) {
                      if (this.$refs.table2.selection[j].username == this.dataList[i].username) {
                          a.push(this.dataList[i])
                      }
                  }
              }
              console.log(a);*/
            //两数组对象，获取不同的两数组对象
            let getArrayList = this.getArrDifSameValue(this.$refs.table2.selection,this.dataList)

            getArrayList.map(it => {
                if(it.id == row.id){
                    let lb = "";
                    it.zbgz =''
                    it.bz =''
                    it.yjkId =''

                    it.yj =''
                    it.yjsList = []

                    getById(row.lb).then(r => {
                        getLbSelect(Object.assign({
                            yjkfl: 'ry',
                            fl: r.data.data.fl
                        })).then(rr => {
                            it.yjsList = [];
                            rr.data.data.map(itt => {

                                let item = {
                                    name:itt.yj,
                                    value:itt.id
                                }

                                it.yjsList.push(item);

                            });

                        });
                    });
                }
            })
        }else {
            row.lb = '';
            row.yj = '';
            row.zbgz ='';
            row.bz = '';
            row.yjkId = '';
            row.lbms = '';
            row.yjms = '';
            row.yjsList = [];
        }


        putObj(row).then((res) => {

            if (res.data.data) {
                this.$notify.closeAll();
                this.$notify.success("保存成功");
            }
            //刷新列表
            this.getDataList();
        });
    },
    savePropertyYj(val,row, index) {
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0) {
            let checked = [];
            let inputId = row.id;
            data.forEach((ele) => {
                checked.push(ele.id);
            });
            if (val != "" && val != null && val != undefined) {
                data.map(it => {

                    if (checked.includes(inputId)) {

                        it.yj = row.yj
                        getLbSelect(Object.assign({
                            yjkfl: 'ry',
                            fl: '',
                            sjkid: row.yj

                        })).then(r => {

                            r.data.data.map(itt => {

                                if (itt.zbgz == 1) {
                                    it.zbgz = '负指标'
                                } else {
                                    it.zbgz = '正指标'
                                }
                                it.bz = itt.jkfbz;
                                it.yjkId = itt.id;
                                it.lbms = itt.fl;
                                it.yjms = itt.yj;

                            })
                        })

                    }
                });
                this.$forceUpdate()
            }else{
                data.map(it => {

                    if(checked.indexOf(inputId) != -1){
                        it.yj = '';
                        it.zbgz ='';
                        it.bz = '';
                        it.yjkId = '';
                        it.lbms = '';
                        it.yjms = '';
                        it.yjsList=[];
                    }

                });
            }
        }
        //未选中的
        if (val != "" && val != null && val != undefined) {
            this.dataList.map(it => {
                if (row.id == it.id) {

                    getLbSelect(Object.assign({
                        yjkfl: 'ry',
                        fl: '',
                        sjkid: row.yj

                    })).then(r => {

                        r.data.data.map(itt => {
                            if (itt.zbgz == 1) {
                                row.zbgz = '负指标'
                            } else {
                                row.zbgz = '正指标'
                            }
                            row.bz = itt.jkfbz;
                            row.yjkId = itt.id;
                            row.lbms = itt.fl;
                            row.yjms = itt.yj
                        })
                    })
                }
            });
        }else{
            row.yj = '';
            row.yjsList=[];
            row.zbgz ='';
            row.bz = '';
            row.yjkId = '';
            row.lbms = '';
            row.yjms = '';

        }
        putObj(row).then((res) => {

            if (res.data.data) {
                this.$notify.closeAll();
                this.$notify.success("保存成功");
            }
            //刷新列表
            this.getDataList();
        });
    },
    // 保存属性
    savePropertyJjx(val,row, index) {
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            let  checked = [];
            let  inputId = row.id;
            data.map(ele => {
                checked.push(ele.id);
            });
            if(val != "" && val != null && val != undefined){
                data.map(it => {

                    if(checked.includes(inputId)){
                        it.jjxId = row.jjxId;

                        this.jjxsList.map(its =>{
                            if(row.jjxId == its.value){
                                it.jjx = its.name;
                            }

                        })

                    }
                });
            }else{
                data.map(it => {

                    if(checked.indexOf(inputId) != -1){

                        it.jjxId = '';
                        //改
                        it.jjx =''

                    }

                });
            }
        }
        //未选中的
        if(val != "" && val != null && val != undefined){

            let getArrayList = this.getArrDifSameValue(this.$refs.table2.selection,this.dataList)

            getArrayList.map(it => {
                if(it.id == row.id){

                    this.jjxsList.map(it =>{
                        if(row.jjxId == it.value){
                            row.jjx = it.name;
                        }

                    })

                }
            })
        }else{
            row.jjx = '';
            row.jjxId = '';

        }
        putObj(row).then((res) => {

            if (res.data.data) {
                this.$notify.closeAll();
                this.$notify.success("保存成功");
            }
            //刷新列表
            this.getDataList();
        });

    },
    savePropertyJkjj(row, index) {
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            let  checked = [];
            let  inputId = row.id;
            data.forEach((ele) => {
                checked.push(ele.id);
            });

            data.forEach((ele) => {

                if(checked.includes(inputId)){

                    ele.jkjj=row.jkjj;

                }
            });
            this.$forceUpdate()
        }
        putObj(row).then((res) => {

            if (res.data.data) {
                this.$notify.closeAll();
                this.$notify.success("保存成功");
            }
            //刷新列表
            this.getDataList();
        });

    },
    // 保存属性
    savePropertyJkfz(row, index) {
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            let  checked = [];
            let  inputId = row.id;
            data.forEach((ele) => {
                checked.push(ele.id);
            });

            data.forEach((ele) => {

                if(checked.includes(inputId)){

                    ele.jkfz=row.jkfz;

                }
            });
            this.$forceUpdate()
        }
        putObj(row).then((res) => {

            if (res.data.data) {
                this.$notify.closeAll();
                this.$notify.success("保存成功");
            }
            //刷新列表
            this.getDataList();
        });

    },
    fatherLb(val,row, index){
        let data = [];
        data = this.$refs.table2.selection;

        if(data.length != 0){

            let checked = []
            let inputId = row.id;
            data.map(it => {
                checked.push(it.id);
            });
        if(val != "" && val != null && val != undefined){

            data.map(it => {

                if(checked.indexOf(inputId) != -1){

                    it.lb = row.lb;

                    //改
                    it.zbgz =''
                    it.bz =''
                    it.yjkId =''
                    it.yj =''
                    it.yjsList = []

                    getById(row.lb).then(r => {

                        getLbSelect(Object.assign({
                            yjkfl: 'ry',
                            fl: r.data.data.fl
                        })).then(r => {
                            it.yjsList = [];
                            r.data.data.map(itt => {
                                let item = {
                                    name:itt.yj,
                                    value:itt.id
                                }

                                it.yjsList.push(item);

                            });

                        });
                    });


                }

            });
        }else{
          data.map(it => {

              if(checked.indexOf(inputId) != -1){

                  it.lb = '';
                  //改
                  it.zbgz =''
                  it.bz =''
                  it.yjkId =''
                  it.yj =''
                  it.yjsList = []

              }

          });
        }
        }
        //未选中的
        if(val != "" && val != null && val != undefined){
          /*
          //两数组对象，去重复，留下一个数组对象
          const arrayObject = this.$refs.table2.selection.concat(this.dataList)
                    let arrys= this.unique(arrayObject);
                    console.log(arrys)*/
          /*
            //两数组对象，获取相同的数组对象
            let a = [];

            for (let i = 0, length = this.dataList.length; i < length; i++) {
                for (let j = 0, l = this.$refs.table2.selection.length; j < l; j++) {
                    if (this.$refs.table2.selection[j].username == this.dataList[i].username) {
                        a.push(this.dataList[i])
                    }
                }
            }
            console.log(a);*/
            //两数组对象，获取不同的两数组对象
            let getArrayList = this.getArrDifSameValue(this.$refs.table2.selection,this.dataList)
            getArrayList.map(it => {
                if(it.id == row.id){
                    let lb = "";
                    it.zbgz =''
                    it.bz =''
                    it.yjkId =''
                    it.yj =''
                    it.yjsList = []

                    getById(row.lb).then(r => {

                        getLbSelect(Object.assign({
                            yjkfl: 'ry',
                            fl: r.data.data.fl
                        })).then(rr => {
                            it.yjsList = [];

                            rr.data.data.map(itt => {

                                let item = {
                                    name:itt.yj,
                                    value:itt.id
                                }

                                it.yjsList.push(item);

                            });

                        });
                    });
                }
            })

        }else{
            row.lb = '';
            row.yj = '';
            row.zbgz ='';
            row.bz = '';
            row.yjkId = '';
            row.lbms = '';
            row.yjms = '';
            row.yjsList = [];
        }

    },
    getArrDifSameValue(arr1,arr2){
      var result = [];
      for(var i = 0; i < arr2.length; i++){
          var obj = arr2[i];
          var username = obj.username;
          var isExist = false;
          for(var j = 0; j < arr1.length; j++){
              var aj = arr1[j];
              var n = aj.username;
              if(n == username){
                  isExist = true;
                  break;
              }
          }
          if(!isExist){
              result.push(obj);
          }
      }
      return result;
    },
    //去重函数
    unique(arr) {
        const res = new Map()
        return arr.filter((arr) => !res.has(arr.username) && res.set(arr.username, 1))
    },
    fatherYj(val,row, index){
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){

            let checked = []
            let inputId = row.id;
            data.map(it => {
                checked.push(it.id);
            });
        if(val != "" && val != null && val != undefined){


            data.map(it => {

                if(checked.includes(inputId)){

                    it.yj = row.yj
                    getLbSelect(Object.assign({
                        yjkfl: 'ry',
                        fl: '',
                        sjkid: row.yj

                    })).then(r => {
                        r.data.data.map(itt =>{

                            if(itt.zbgz == 1){
                                it.zbgz ='负指标'
                            }else{
                                it.zbgz ='正指标'
                            }
                            it.bz = itt.jkfbz;
                            it.yjkId = itt.id;
                            it.lbms = itt.fl;
                            it.yjms = itt.yj;

                        })
                    })

                }
            });
        }else{
                data.map(it => {

                    if(checked.indexOf(inputId) != -1){
                        it.yj = '';
                        it.zbgz ='';
                        it.bz = '';
                        it.yjkId = '';
                        it.lbms = '';
                        it.yjms = '';
                        //it.yjsList = [];
                    }

                });
            }
        }
        //未选中的
        if(val != "" && val != null && val != undefined){
            this.dataList.map(it => {
                if (row.id == it.id) {

                    getLbSelect(Object.assign({
                        yjkfl: 'ry',
                        fl: '',
                        sjkid: row.yj

                    })).then(r => {
                        r.data.data.map(itt => {
                            if (itt.zbgz == 1) {
                                row.zbgz = '负指标'
                            } else {
                                row.zbgz = '正指标'
                            }
                            row.bz = itt.jkfbz;
                            row.yjkId = itt.id;
                            row.lbms = itt.fl;
                            row.yjms = itt.yj;
                        })
                    })
                }
            });
        }else{
            row.yj = '';
            row.zbgz ='';
            row.bz = '';
            row.yjkId = '';
            row.lbms = '';
            row.yjms = '';
            //row.yjsList = [];
        }
    },
    fatherJkfz(row, index){
        if(row !=null && row !="") {
            let data = [];
            data = this.$refs.table2.selection;
            if (data.length != 0) {
                let checked = [];
                let inputId = row.id;
                data.forEach((ele) => {
                    checked.push(ele.id);
                });

                data.forEach((ele) => {

                    if (checked.includes(inputId)) {

                        ele.jkfz = row.jkfz;

                    }
                });
                this.$forceUpdate()
            }
        }
    },
    fatherJkjj(row, index){
        if(row !=null && row !="") {
          let data = [];
          data = this.$refs.table2.selection;
          if(data.length != 0){
              let  checked = [];
              let  inputId = row.id;
              data.forEach((ele) => {
                  checked.push(ele.id);
              });

              data.forEach((ele) => {

                  if(checked.includes(inputId)){

                      ele.jkjj=row.jkjj;

                  }
              });
              this.$forceUpdate()
          }
        }
    },
    fatherJjx(val,row, index){
        let data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            let  checked = [];
            let  inputId = row.id;
            data.map(ele => {
                checked.push(ele.id);
            });
            if(val != "" && val != null && val != undefined){
              data.map(it => {

                  if(checked.includes(inputId)){
                      it.jjxId = row.jjxId;

                      this.jjxsList.map(its =>{
                          if(row.jjxId == its.value){
                              it.jjx = its.name;
                          }

                      })

                  }
              });
            }else{
                data.map(it => {

                    if(checked.indexOf(inputId) != -1){

                        it.jjxId = '';
                        //改
                        it.jjx =''

                    }

                });
            }
        }
        //未选中的
        if(val != "" && val != null && val != undefined){

        let getArrayList = this.getArrDifSameValue(this.$refs.table2.selection,this.dataList)

          getArrayList.map(it => {
              if(it.id == row.id){

              this.jjxsList.map(it =>{
                  if(row.jjxId == it.value){
                      row.jjx = it.name;
                  }

              })

              }
          })
        }else{
            row.jjx = '';
            row.jjxId = '';

        }

    },
    //打开人员
    checkPerson(type) {
        if (type == "sjkh") {
            this.usercomment = true;
            this.$nextTick(() => {
                //this.$refs.usercomment.init({}, "sjkh", JSON.stringify(this.dataList));  //fakeData
                this.$refs.usercomment.init("", type, JSON.stringify(this.dataList),"","htcj");  //fakeData

            });
        }

    },
    //选取后列表
    submitfy(data) {

        let personList = data.tableDataUser.map(it => {
            return {
                cyrUserId: it.userId,
                cyrRealName: it.userName,
                cyrDeptId: it.deptId,
                cyrDeptName: it.deptName,
                cyrUserName: it.userCode
            };
        });

        personList.forEach((ele) => {
            var item = {
              id:this.index,
              ygid : ele.cyrUserId,
              realname :ele.cyrRealName,
              deptid:ele.cyrDeptId,
              deptName:ele.cyrDeptName,
              username: ele.cyrUserName,
              bz:'',
              zbgz:'',
              lb:'',
              yj:'',
              lbsList:[],
              yjsList:[],
              jkfz:'0',
              jjx:'',
              jjxId:'',
              jkjj:'0',
              yjkId:'',
              lbms:'',
              yjms:''

            };
            this.index++;
            this.dataList.push(item);

          /*const arr = [...this.dataList, ...Object.assign(personList)]; //父子数据合并
          const newArr = arr.reduce(function (tempArr, item) { //去重
            if (tempArr.findIndex((ele) => parseInt(ele.ygid) === parseInt(item.ygid)) === -1) {
              tempArr.push(item)
            }
            return tempArr
          }, []);
          this.dataList = newArr ; //去重后的数据*/

        });
    },
    //子组件列表
    getDataList() {

      this.dataListLoading = true;
        getKhdxList(
            Object.assign({
            sjkhId:this.sjkhId
            })
        ).then(r => {
            this.dataList = response.data.data.records;
            this.totalPage = response.data.data.total;
        });
        this.dataListLoading = false;

    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    //联动追加1
    appendTolb(val){
      let data = [];
      data = this.$refs.table2.selection;

      if(data.length != 0){
          data.forEach((ele) => {

              if(val != null || val !=""){
                  if(ele.lb != null || ele.lb !=""){
                      ele.lb = val;
                      ele.yj = '';
                      ele.yjsList = [];
                  }
              }
          });
      }
    },
    //联动追加2
    appendTozb(obj1,obj2){
        var data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            data.forEach((ele) => {
                   ele.zbgz = obj1;
                   ele.bz = obj2;
            });
            this.$forceUpdate()
        }

    },
    //联动追加3
    appendTojkfz(obj){
        var data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            data.forEach((ele) => {
                ele.jkfz = obj;
            });
            this.$forceUpdate()
        }

    },
    //联动追加4
    appendTojjx(obj){
        var data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            data.forEach((ele) => {
                ele.jjx = obj;
            });
            this.$forceUpdate()
        }
    },
    //联动追加5
    appendTojkjj(obj){
        var data = [];
        data = this.$refs.table2.selection;
        if(data.length != 0){
            data.forEach((ele) => {
                ele.jkjj = obj;
            });
            this.$forceUpdate()
        }
    },
    //修改页面删除列
    deleteBatch() {
        var data = [];
        data = this.$refs.table2.selection;

        if (data.length == 0) {
            this.$message.closeAll();
            this.$message.error("请至少选择一个！");
            return;
        }

            this.$confirm("是否要删除吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {

                    this.dataList = this.testa(
                        this.$refs.table2.selection,
                        this.dataList
                    );
                     this.updateDeptData();

                })
                .catch(() => {});

    },
    updateDeptData() {
        let id = this.$refs.table2.selection.map(it => {
            return it.id;
        });

        deleteChildEvent(id.toString()).then(r => {
            if (r.data.code == 0) {
                this.$message.success("删除成功");
                this.getDataList();
            } else {
                this.$message.error(r.data.msg);
                this.getDataList();
            }
        });

    },
    testa(array1, array2) {
        var result = [];
        for (var i = 0; i < array2.length; i++) {
            var obj = array2[i];
            var num = obj.id;
            var isExist = false;
            for (var j = 0; j < array1.length; j++) {
                var aj = array1[j];
                var n = aj.id;
                if (n == num) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                result.push(obj);
            }
        }
        return result;
    },

    //新加导出 动态导出
      download() {
          // var data = this.multipleSelection;
          // if (data.length == 0) {
          //     this.$message.closeAll();
          //     this.$message.warning("请选择一个工作！");
          //     return;
          // }
          var filename = "人员信息导入模板" + ".xlsx";
          // var ids = [];
          // for (var i = 0; i < data.length; i++) {
          //     ids.push(data[i].id);
          // }
          exportExcel({
              ids: ''
          }).then(response => {
              this.$message.closeAll();
              this.$message.success("导出成功!");
              let url = window.URL.createObjectURL(new Blob([response.data]));
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              link.setAttribute("download", filename);
              document.body.appendChild(link);
              link.click();
          });
      },

      //导入
      openExportModal(){
          this.innerVisible = true;
      },
  },
};
</script>

<style>

</style>
